#include "socket.h"


#define IPSTR   "ipstr="
#define PORTSTR "port="
#define LISMAX  "lismax="

struct conf_info
{
    char ips[32];
    short port;
    short lismax;
};

//读取配置信息
int read_conf(struct conf_info *p)
{
    FILE *fp = fopen("my.conf", "r");
    if (fp == NULL)
    {
        printf("open my.conf err\n");
        return -1;
    }

    int line = 0;
    while (true)
    {
        char buff[128] = {0};
        if (fgets(buff, 127, fp) == NULL)
        {
            break;
        }

        buff[strlen(buff) - 1] = '\0';//去除尾部\n
        line++;//记录文件行数
        //跳过空行
        if (buff[0] == '\0')
        {
            continue;
        }
        //跳过注释
        if (buff[0] == '#')
        {
            continue;
        }

        if (strncmp(buff, IPSTR, strlen(IPSTR)) == 0)
        {
            strcpy(p->ips, buff + strlen(IPSTR));
        }
        else if (strncmp(buff, PORTSTR, strlen(PORTSTR)) == 0)
        {
            p->port = atoi(buff + strlen(PORTSTR));
        }
        else if (strncmp(buff, LISMAX, strlen(LISMAX)) == 0)
        {
            p->lismax = atoi(buff + strlen(LISMAX));
        }
        else
        {
            printf("不识别的匹配项 %s in line : %d \n", buff, line);
        }
    }

    fclose(fp);
    return 0;
}

int socket_init() 
{
    //读取配置文件，获取ip port lismax
    struct conf_info dt;
    if (read_conf(&dt) == -1)
    {
        return -1;
    }

    printf("ip:%s\n", dt.ips);
    printf("port:%d\n", dt.port);
    printf("lismax:%d\n", dt.lismax);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
        return -1;
    struct sockaddr_in saddr;
    memset(&saddr, 0, sizeof(saddr));
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(dt.port);
    saddr.sin_addr.s_addr = inet_addr(dt.ips);

    int res = bind(sockfd, (struct sockaddr*)&saddr, sizeof(saddr));
    if (res == -1)
    {
        return -1;
    }
    res = listen(sockfd, dt.lismax);
    if (res == -1)
    {
        return -1;
    }

    return sockfd;
}